package com.iwhalecloud.citybrain.flow.platform.manager.application.service.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.iwhalecloud.citybrain.flow.platform.manager.application.common.context.ModelDeploymentContext;
import com.iwhalecloud.citybrain.flow.platform.manager.application.service.ModelDeploymentPostProcessor;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.model.FlowTitleExpression;
import com.iwhalecloud.citybrain.flow.platform.manager.domain.repository.FlowTitleExpressionRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 流程部署 取流程自定义标题
 *
 * @author: lzb
 * @date: 2021/12/9 22:16
 */
@Slf4j
@Component
public class SaveFlowFormTitleProcessor implements ModelDeploymentPostProcessor {

    @Autowired
    private FlowTitleExpressionRepository flowTitleExpressionRepository;

    @Override
    public void process(ModelDeploymentContext context) {
        JsonNode modelJson = context.getModelJson();
        if (Objects.nonNull(modelJson)) {
            JsonNode customTitleConfigNode = modelJson.get("properties");
            if (Objects.nonNull(customTitleConfigNode)) {
                JsonNode customTitleConfigNodeObj = customTitleConfigNode.get("customTitle");
                List<String> nodeCustomTitleExpression = new ArrayList<>();
                if (Objects.nonNull(customTitleConfigNodeObj)){
                    for (int i = 0; i < customTitleConfigNodeObj.size(); i++) {
                        JsonNode customTitleInfo = customTitleConfigNodeObj.get(i);
                        String titleExpression = customTitleInfo.get("titleExpression").textValue();
                        nodeCustomTitleExpression.add(titleExpression);
                    }
                    handleCustomTitleExpression(nodeCustomTitleExpression, context);
                }
            }
        }


    }

    public void handleCustomTitleExpression(List<String> expressionList, ModelDeploymentContext context) {
        if (!CollectionUtils.isEmpty(expressionList)) {
            String titleExpression = String.join(",", expressionList);
            FlowTitleExpression flowTitleExpression = new FlowTitleExpression();
            flowTitleExpression.setDeployId(context.getDeployId());
            flowTitleExpression.setExpression(titleExpression);
            flowTitleExpressionRepository.insertFlowTitleExpression(flowTitleExpression);
        }
    }
}
